#include "cameraWidget.h"
//#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)//,
    //ui(new Ui::MainWindow)
{
    //ui->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);//关闭时回收内存

    thread = new Thread(this);
    connect(thread, &Thread::image, this, &MainWindow::image);
    thread->start();

    this->setFixedSize(1024, 600);

    connect(KeyThread::Get(), &KeyThread::keyEvent, this, &MainWindow::KeyEvent);

    timer.setInterval(1500);
    timer.setSingleShot(true);
    connect(&timer, &QTimer::timeout, this, [&]
    {
        //close();
    });

    this->setAttribute(Qt::WA_AcceptTouchEvents);
}

MainWindow::~MainWindow()
{
    //delete ui;
    thread->isExit = true;
    thread->wait();
    emit sigClose();
}

void MainWindow::mousePressEvent(QMouseEvent *)
{
    timer.start();
}

void MainWindow::mouseReleaseEvent(QMouseEvent *)
{
    timer.stop();
}


void MainWindow::paintEvent(QPaintEvent *)
{
    if (img.isNull()) return;

    static View_n v = view;
    if(v != view)
    {
        qDebug() << "view = " << view;
        v = view;
    }
    QMutexLocker lock(&mutex);
    QPainter painter(this);
    if(view == VIEW_ONE)
    {
        QImage image;

        switch (scale)
        {
            case SCALE_0_4:
            {
                painter.fillRect(rect(), QBrush(Qt::black));
                image = img.scaled(width()*0.4, height()*0.4);
            }
            break;
            case SCALE_0_6:
            {
                painter.fillRect(rect(), QBrush(Qt::black));
                image = img.scaled(width()*0.6, height()*0.6);
            }
            break;
            case SCALE_0_8:
            {
                painter.fillRect(rect(), QBrush(Qt::black));
                image = img.scaled(width()*0.8, height()*0.8);
            }
            break;
            case SCALE_1_0:
            {
                image = img.scaled(width(), height());
            }
            break;
            case SCALE_1_2:
            {
                image = img.scaled(width()*1.2, height()*1.2);
            }
            break;
            case SCALE_1_4:
            {
                image = img.scaled(width()*1.4, height()*1.4);
            }
            break;
            case SCALE_1_6:
            {
                image = img.scaled(width()*1.6, height()*1.6);
            }
            break;
            case SCALE_1_8:
            {
                image = img.scaled(width()*1.8, height()*1.8);
            }
            break;
            case SCALE_2_0:
            {
                image = img.scaled(width()*2.0, height()*2.0);
            }
            break;
            default:
            {
                break;
            }
        }

        //qDebug() << image.width() << " " << image.height();
        img_oneView_static = image;
        painter.drawImage(QPoint((width()-img_oneView_static.width())/2, (height()-img_oneView_static.height())/2),img_oneView_static);
    }
    else if(view == VIEW_ONE_STATIC)
    {
        if(img_oneView_static.isNull())
            img_oneView_static = img;
        painter.drawImage(QPoint((width()-img_oneView_static.width())/2, (height()-img_oneView_static.height())/2),img_oneView_static);
    }
    else if(view == VIEW_TWO)
    {
        QImage image = img.scaled(width()/2, height());
        img_twoView_static1 = image;
        painter.drawImage(QPoint(0, 0),image);
        painter.drawImage(QPoint(width()/2, 0),image);
    }
    else if(view==VIEW_TWO_STATIC_FIRST)
    {
        QImage image = img.scaled(width()/2, height());
        if(img_twoView_static1.isNull())
            img_twoView_static1 = image;
        img_twoView_static2 = image;
        painter.drawImage(QPoint(0, 0),img_twoView_static1);
        painter.drawImage(QPoint(width()/2, 0),image);
    }
    else if(view==VIEW_TWO_STATIC_SECOND)
    {
        QImage image = img.scaled(width()/2, height());
        if(img_twoView_static1.isNull())
            img_twoView_static1 = image;
        if(img_twoView_static2.isNull())
            img_twoView_static2 = image;
        painter.drawImage(QPoint(0, 0),img_twoView_static1);
        painter.drawImage(QPoint(width()/2, 0),img_twoView_static2);
    }
    else if(view==VIEW_TWO_STATIC_SECOND_ONLY)
    {
        QImage image = img.scaled(width()/2, height());
        if(img_twoView_static2.isNull())
            img_twoView_static2 = image;
        painter.drawImage(QPoint(0, 0),image);
        painter.drawImage(QPoint(width()/2, 0),img_twoView_static2);
    }
    else if(view == VIEW_FOUR)
    {
        QImage image = img.scaled(width()/2, height()/2);

        img_fourView_static1 = image;
        painter.drawImage(QPoint(0, 0),image);
        painter.drawImage(QPoint(width()/2, 0),image);
        painter.drawImage(QPoint(0, height()/2),image);
        painter.drawImage(QPoint(width()/2, height()/2),image);
    }
    else if(view == VIEW_FOUR_STATIC_FIRST)
    {
        QImage image = img.scaled(width()/2, height()/2);

        if(img_fourView_static1.isNull())
            img_fourView_static1 = image;

        img_fourView_static2 = image;
        painter.drawImage(QPoint(0, 0),img_fourView_static1);
        painter.drawImage(QPoint(width()/2, 0),image);
        painter.drawImage(QPoint(0, height()/2),image);
        painter.drawImage(QPoint(width()/2, height()/2),image);
    }
    else if(view == VIEW_FOUR_STATIC_SECOND)
    {
        QImage image = img.scaled(width()/2, height()/2);

        if(img_fourView_static1.isNull())
            img_fourView_static1 = image;
        if(img_fourView_static2.isNull())
            img_fourView_static2 = image;

        img_fourView_static3 = image;
        painter.drawImage(QPoint(0, 0),img_fourView_static1);
        painter.drawImage(QPoint(width()/2, 0),img_fourView_static2);
        painter.drawImage(QPoint(0, height()/2),image);
        painter.drawImage(QPoint(width()/2, height()/2),image);
    }
    else if(view == VIEW_FOUR_STATIC_THIRD)
    {
        QImage image = img.scaled(width()/2, height()/2);

        if(img_fourView_static1.isNull())
            img_fourView_static1 = image;
        if(img_fourView_static2.isNull())
            img_fourView_static2 = image;
        if(img_fourView_static3.isNull())
            img_fourView_static3 = image;

        img_fourView_static4 = image;
        painter.drawImage(QPoint(0, 0),img_fourView_static1);
        painter.drawImage(QPoint(width()/2, 0),img_fourView_static2);
        painter.drawImage(QPoint(0, height()/2),img_fourView_static3);
        painter.drawImage(QPoint(width()/2, height()/2),image);
    }
    else if(view == VIEW_FOUR_STATIC_FOURTH)
    {
        QImage image = img.scaled(width()/2, height()/2);

        if(img_fourView_static1.isNull())
            img_fourView_static1 = image;
        if(img_fourView_static2.isNull())
            img_fourView_static2 = image;
        if(img_fourView_static3.isNull())
            img_fourView_static3 = image;
        if(img_fourView_static4.isNull())
            img_fourView_static4 = image;

        painter.drawImage(QPoint(0, 0),img_fourView_static1);
        painter.drawImage(QPoint(width()/2, 0),img_fourView_static2);
        painter.drawImage(QPoint(0, height()/2),img_fourView_static3);
        painter.drawImage(QPoint(width()/2, height()/2),img_fourView_static4);
    }
    else if(view == VIEW_FOUR_FREE_ONE)
    {
        QImage image = img.scaled(width()/2, height()/2);
        painter.drawImage(QPoint(0, 0),image);
        painter.drawImage(QPoint(width()/2, 0),img_fourView_static2);
        painter.drawImage(QPoint(0, height()/2),img_fourView_static3);
        painter.drawImage(QPoint(width()/2, height()/2),img_fourView_static4);
    }
    else if(view == VIEW_FOUR_FREE_TWO)
    {
        QImage image = img.scaled(width()/2, height()/2);
        painter.drawImage(QPoint(0, 0),image);
        painter.drawImage(QPoint(width()/2, 0),image);
        painter.drawImage(QPoint(0, height()/2),img_fourView_static3);
        painter.drawImage(QPoint(width()/2, height()/2),img_fourView_static4);
    }
    else if(view == VIEW_FOUR_FREE_THREE)
    {
        QImage image = img.scaled(width()/2, height()/2);
        painter.drawImage(QPoint(0, 0),image);
        painter.drawImage(QPoint(width()/2, 0),image);
        painter.drawImage(QPoint(0, height()/2),image);
        painter.drawImage(QPoint(width()/2, height()/2),img_fourView_static4);
    }
}

void MainWindow::image(uchar *rgb)
{
    //qDebug() << rgb.size();

    QImage tmpImg((uchar *)rgb,640,480,QImage::Format_RGB888);
    QMutexLocker lock(&mutex);
    img = tmpImg.copy();
    update();
}

void MainWindow::KeyEvent(Key_t type, int key)
{
    //qDebug() << "MainWindow--key=" << key << " type=" << type;
    if(key == 0)
    {
        if(type == KEY_PRESS)
        {
            switch(view)
            {
                case VIEW_ONE:
                case VIEW_ONE_STATIC:
                {
                    view = VIEW_TWO;
                    break;
                }
                case VIEW_TWO:
                case VIEW_TWO_STATIC_FIRST:
                case VIEW_TWO_STATIC_SECOND:
                case VIEW_TWO_STATIC_SECOND_ONLY:
                {
                    view = VIEW_FOUR;
                    break;
                }
                case VIEW_FOUR:
                case VIEW_FOUR_STATIC_FIRST:
                case VIEW_FOUR_STATIC_SECOND:
                case VIEW_FOUR_STATIC_THIRD:
                case VIEW_FOUR_STATIC_FOURTH:
                case VIEW_FOUR_FREE_ONE:
                case VIEW_FOUR_FREE_TWO:
                case VIEW_FOUR_FREE_THREE:
                {
                    view = VIEW_ONE;
                    break;
                }
                default:
                {
                    view = VIEW_ONE;
                    break;
                }
            }

        }
    }
    else if(key == 1)
    {
        if(type == KEY_PRESS)
        {
            switch (view)
            {
                case VIEW_ONE:
                {
                    view = VIEW_ONE_STATIC;
                    QMutexLocker lock(&mutex);
                    saveImg(img_oneView_static, VIEW_ONE_PATH);
                    break;
                }
                case VIEW_ONE_STATIC:
                {
                    view = VIEW_ONE;
                    break;
                }
                case VIEW_TWO:
                {
                    view = VIEW_TWO_STATIC_FIRST;
                    QMutexLocker lock(&mutex);
                    saveImg(img_twoView_static1, VIEW_TWO_PATH1);
                    break;
                }
                case VIEW_TWO_STATIC_FIRST:
                {
                    view = VIEW_TWO_STATIC_SECOND;
                    QMutexLocker lock(&mutex);
                    saveImg(img_twoView_static2, VIEW_TWO_PATH2);
                    break;
                }
                case VIEW_TWO_STATIC_SECOND:
                {
                    view = VIEW_TWO_STATIC_SECOND_ONLY;
                    break;
                }
                case VIEW_TWO_STATIC_SECOND_ONLY:
                {
                    view = VIEW_TWO;
                    break;
                }
                case VIEW_FOUR:
                {
                    view = VIEW_FOUR_STATIC_FIRST;
                    QMutexLocker lock(&mutex);
                    saveImg(img_fourView_static1, VIEW_FOUR_PATH1);
                    break;
                }
                case VIEW_FOUR_STATIC_FIRST:
                {
                    view = VIEW_FOUR_STATIC_SECOND;
                    QMutexLocker lock(&mutex);
                    saveImg(img_fourView_static2, VIEW_FOUR_PATH2);
                    break;
                }
                case VIEW_FOUR_STATIC_SECOND:
                {
                    view = VIEW_FOUR_STATIC_THIRD;
                    QMutexLocker lock(&mutex);
                    saveImg(img_fourView_static3, VIEW_FOUR_PATH3);
                    break;
                }
                case VIEW_FOUR_STATIC_THIRD:
                {
                    view = VIEW_FOUR_STATIC_FOURTH;
                    QMutexLocker lock(&mutex);
                    saveImg(img_fourView_static3, VIEW_FOUR_PATH4);
                    break;
                }
                case VIEW_FOUR_STATIC_FOURTH:
                {
                    view = VIEW_FOUR_FREE_ONE;
                    break;
                }
                case VIEW_FOUR_FREE_ONE:
                {
                    view = VIEW_FOUR_FREE_TWO;
                    break;
                }
                case VIEW_FOUR_FREE_TWO:
                {
                    view = VIEW_FOUR_FREE_THREE;
                    break;
                }
                case VIEW_FOUR_FREE_THREE:
                {
                    view = VIEW_FOUR;
                    break;
                }
                default:break;
            }

        }
    }
    else if(key == 2)
    {
        if(type == KEY_CLICK)
        {
            if(view == VIEW_ONE)
            {
                int count = (int)scale;
                count++;

                count %= (int)SCALE_MAX;
                scale = (Scale_n)count;
            }
        }
        else if(type == KEY_LONG_PRESS)
        {
            close();
        }
    }
}

void MainWindow::saveImg(QImage img, QString name)
{
    if(Server::Get()->isSD2In)
    {
        disconnect(KeyThread::Get(), &KeyThread::keyEvent, this, &MainWindow::KeyEvent);
        QString data = "请先插入TF卡";
        TipWidget *t = new TipWidget(data);
        t->show();
        connect(t, &TipWidget::sigClose, this, [&]
        {
            connect(KeyThread::Get(), &KeyThread::keyEvent, this, &MainWindow::KeyEvent);
        });
    }

    if(img.isNull())
    {
        log_debug() << "NULL, save fail";
        return ;
    }
    QPainter pp(&img);

    QPen pen = QPen(Qt::red,5);
    QFont f;
    f.setPixelSize(50);
    f.setBold(true);
    pp.setFont(f);
    QBrush brush = QBrush(Qt::red);

    pp.setPen(pen);

    pp.setBrush(brush);

    pp.drawText(QRectF(10.0,10.0, 100, 100), name);

    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("yyyy.MM.dd_hh.mm.ss");//.zzz
    bool ret = img.save(PATH+name +"/"+ current_date + ".png");
    if(!ret)
        log_debug() << "save img fail:"<< img.size();

    static bool flag = false;
    unsigned long long data = 0;
    int r = space::getMemory(PATH, data);
    if(r >= 0)
    {
        if(data <= QT_USE_SPACE && !flag)
        {
            disconnect(KeyThread::Get(), &KeyThread::keyEvent, this, &MainWindow::KeyEvent);
            flag = true;
            QString data = "剩余内存不多，请尽快清理";
            TipWidget *t = new TipWidget(data);
            t->show();
            connect(t, &TipWidget::sigClose, this, [&]
            {
                connect(KeyThread::Get(), &KeyThread::keyEvent, this, &MainWindow::KeyEvent);
            });
        }
    }
}

bool MainWindow::event(QEvent *e)
{
    static int index = 0;
    static qreal _lastScaleFactor = 0.0;
    static int move = 0;
    switch (e->type())
    {
        case QEvent::TouchBegin:
        case QEvent::TouchUpdate:
        case QEvent::TouchEnd:
        {
            //qDebug() <<"CProjectionPicture::event"<<e->type();
            QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
            QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
            if (touchPoints.count() == 2)
            {
                //缩放
                const QTouchEvent::TouchPoint &touchPoint0 = touchPoints.first();
                const QTouchEvent::TouchPoint &touchPoint1 = touchPoints.last();
                qreal currentScaleFactor = QLineF(touchPoint0.pos(), touchPoint1.pos()).length()
                        / QLineF(touchPoint0.startPos(), touchPoint1.startPos()).length();
                if (currentScaleFactor  > _lastScaleFactor)
                    index++;
                else if (currentScaleFactor  < _lastScaleFactor)
                    index--;
                if (index == 5)//超过5次放大，则认为有效.防抖操作
                {
                    index = 0;
                    //zoomOnce(true);
                    if(view == VIEW_ONE)
                    {
                        int count = (int)scale;
                        count++;

                        if(count > (int)SCALE_2_0)
                            count = (int)SCALE_2_0;
                        scale = (Scale_n)count;
                    }
                    qDebug() << "big";
                }
                else if (index == -5)
                {
                    index = 0;
                    //zoomOnce(false);
                    qDebug() << "small";
                    if(view == VIEW_ONE)
                    {
                        int count = (int)scale;
                        if(count > (int)SCALE_0_4)
                            count--;
                        scale = (Scale_n)count;
                    }
                }
                //qDebug()<<index<<currentScaleFactor<<_lastScaleFactor;
                _lastScaleFactor = currentScaleFactor;

                update();
            }
            else if (touchPoints.count() == 1)
            {
                const QTouchEvent::TouchPoint &touchPoint0 = touchPoints.first();
                const auto& pos = touchPoint0.pos();
                const auto& posLast = touchPoint0.lastPos();
                const auto& posDelta = pos - posLast;
                auto dx = int(posDelta.x());
                //auto dy = int(posDelta.y());
                if(abs(dx) >= 30 && !timer.isActive())//|| dy != 0
                {
                    /// 有效的平移系数（delta值）
                    /// 使用dx和dy进行位置平移
                    qDebug() << "move";
                    move = dx;
                }
            }
            if (touchEvent->touchPointStates() & Qt::TouchPointReleased)
            {
                //qDebug()<<"Qt::TouchPointReleased:" << move;
                if(move > 0)
                {

                }
                else if(move < 0)
                {

                }
                move = 0;
            }
            return true;
        }
        default:
            break;
    }

    return QWidget::event(e);
}



